#pragma once
#include <afxwin.h>
#include <vector>
#include "../sqlite3/sqlite3.h"

class CSQLiteStmt {
	protected:
		::sqlite3_stmt* m_pStmt;

	public:
		/**
		 * Constructors & destructors stuff
		 */
		CSQLiteStmt( void ) {
			this->m_pStmt = NULL;
		}

		CSQLiteStmt( ::sqlite3_stmt* pStmt ) {
			this->m_pStmt = pStmt;
		}

		~CSQLiteStmt( void ) {
			if( this->m_pStmt )
				::sqlite3_finalize( this->m_pStmt );
		}

		/**
		 * Fetch one row
		 */
		std::vector<CString> FetchRow( void ) {
			std::vector<CString> out;
			if( !this->m_pStmt ) {
				return out;
			}
			int cols = ::sqlite3_column_count( this->m_pStmt );
			if( ::sqlite3_step( this->m_pStmt ) == SQLITE_ROW ) {
				for( int col = 0; col < cols; col++ ) {
					#ifdef UNICODE
						out.push_back( CString( (const wchar_t*)::sqlite3_column_text16( this->m_pStmt, col ) ) );
					#else
						out.push_back( CString( (const char*)::sqlite3_column_text( this->m_pStmt, col ) ) );
					#endif
				}
			}
			return out;
		}

		/**
		 * Fetch all as std::string of std::string array
		 */
		std::vector<std::vector<CString>> FetchAll( void ) {
			std::vector<std::vector<CString>> out;
			if( !this->m_pStmt ) {
				return out;
			}
			while( true ) {
				std::vector<CString> row = this->FetchRow();
				if( row.size() ) {
					out.push_back( row );
				}
				else {
					break;
				}
			}
			return out;
		}

		/**
		 * Can be helpful
		 */
		const ::sqlite3_stmt* GetStmt( void ) const {
			return this->m_pStmt;
		}

		/**
		 * Useful for counts
		 */
		INT ToInt( void ) {
			if( !this->m_pStmt ) {
				return 0;
			}
			int cols = ::sqlite3_column_count( this->m_pStmt );
			if( cols == 0 ) {
				return 0;
			}
			return ::sqlite3_column_int( this->m_pStmt, 0 );
		}

		/**
		 * Useful for counts
		 */
		INT64 ToInt64( void ) {
			if( !this->m_pStmt ) {
				return 0;
			}
			int cols = ::sqlite3_column_count( this->m_pStmt );
			if( cols == 0 ) {
				return 0;
			}
			return ::sqlite3_column_int64( this->m_pStmt, 0 );
		}	
};